﻿using System;

namespace WpfClient.Model
{
    public class DataService : IDataService
    {
        private EP.Session _session = new EP.Session();
        private EP.RssFeedServiceClient _cli = new EP.RssFeedServiceClient();
        private EP.RssFeed[] _feeds = new EP.RssFeed[] { };

        public void GetFeedList(Action<FeedList, Exception> callback)
        {
            EP.Session session = new EP.Session();
            EP.RssFeedServiceClient cli = new EP.RssFeedServiceClient();
            EP.RssFeed[] feeds = new EP.RssFeed[] {};

            _cli.startSessionCompleted += (object s, EP.startSessionCompletedEventArgs a) => _cli_startSessionCompleted(s, a, callback);
            _cli.startSessionAsync("toto@gmail.com", "coucou", EP.ServiceDevice.WPF);
        }

        void _cli_startSessionCompleted(object sender, EP.startSessionCompletedEventArgs e, Action<FeedList, Exception> callback)
        {
            _cli.ListRssFeedCompleted += (object s, EP.ListRssFeedCompletedEventArgs a) => _cli_ListRssFeedCompleted(s, a, callback);
            _cli.ListRssFeedAsync(e.Result);

        }

        void _cli_ListRssFeedCompleted(object sender, EP.ListRssFeedCompletedEventArgs e, Action<FeedList, Exception> callback)
        {
            var feedlist = new FeedList(e.Result);
            callback(feedlist, null);

        }

        public void GetFeedItemList(Action<FeedItemList, Exception> callback, int feedId)
        {
            EP.RssFeedItem[] feedTab = new EP.RssFeedItem[] { };
            EP.Session session = new EP.Session();
            EP.RssFeed feed = new EP.RssFeed();
            feed.id = feedId;
            session = _cli.startSession("toto@gmail.com", "coucou", EP.ServiceDevice.WPF);
            //_cli.startSessionCompleted += new EventHandler<EP.startSessionCompletedEventArgs>(cli_startSessionCompleted);
            //_cli.startSessionAsync("toto@gmail.com", "coucou", EP.ServiceDevice.WPF);
            //feed = _cli.Subscribe(session, feed);
            
            feedTab = _cli.ListRssFeedItem(session, feed);
            
            var feedlist = new FeedItemList(feedTab);
            callback(feedlist, null);
        }

        void cli_startSessionCompleted(object sender, EP.startSessionCompletedEventArgs e)
        {
            _session = e.Result;

        }

        public void ReadItem(int idItem)
        {
            EP.RssFeedItem item = new EP.RssFeedItem();
            EP.Session session = new EP.Session();
            item.id = idItem;
            session = _cli.startSession("toto@gmail.com", "coucou", EP.ServiceDevice.WPF);
            _cli.ReadSate(session, item, true);
        }
    }
}